package com.hjj.springboot.controller.rider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.constant.SystemConstant;
import com.hjj.springboot.entity.R;
import com.hjj.springboot.entity.Rider;
import com.hjj.springboot.entity.WxUserInfo;
import com.hjj.springboot.service.IRiderService;
import com.hjj.springboot.util.DateUtil;
import com.hjj.springboot.util.JwtUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/rider/user")
public class RiderUserController {

    @Autowired
    private IRiderService riderService;

    @Value("${avatarUrlImagesFilePath}")
    private String avatarUrlImagesFilePath;

    @RequestMapping("/getRiderName")
    public R getRiderName(Integer riderId){
        Rider rider = riderService.getById(riderId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("riderName",rider.getName());
        return R.ok(map);
    }

    @GetMapping("/login")
    public R login(String telNumber,String password){
        Rider rider = riderService.getOne(new QueryWrapper<Rider>().eq("telNumber",telNumber).eq("password",password));
        if(rider==null){
            return R.error("用户不存在或密码错误");
        }
        if(!rider.isPass()){
            return R.error("用户未通过审核");
        }
        rider.setLastLoginDate(new Date());
        riderService.updateById(rider);
        // 利用jwt生成token返回到前端
        String token = JwtUtils.createJWT(String.valueOf(rider.getId()), rider.getTelNumber(), SystemConstant.JWT_TTL);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("userInfo",rider);
        return R.ok(map);
    }

    @PostMapping("/register")
    public R register(@RequestBody Rider rider){
        Rider reslutRider = riderService.getOne(new QueryWrapper<Rider>().eq("telNumber",rider.getTelNumber()));
        if(reslutRider!=null){
            return R.error("用户已存在");
        }
        rider.setRegisterDate(new Date());
        riderService.save(rider);
        return R.ok("注册成功");
    }

    //    上传头像
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(@RequestParam("avatarUrl") MultipartFile file) throws Exception {
        Map<String,Object> reultMap=new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(avatarUrlImagesFilePath+newFileName));
            reultMap.put("code",0);
            reultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","img/avatarUrl/"+newFileName);
            reultMap.put("data",dataMap);
        }
        return reultMap;
    }

    @RequestMapping("/getNum")
    public R getNum(int id){
        Rider rider = riderService.getById(id);
        LocalDate start = rider.getRegisterDate().toInstant()
                .atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate end = new Date().toInstant()
                .atZone(ZoneId.systemDefault()).toLocalDate();
        long days = ChronoUnit.DAYS.between(start, end) + 1;
        HashMap<String, Object> map = new HashMap<>();
        map.put("days",Math.max(days,1));
        return R.ok(map);
    }

    @PostMapping("/updateInfo")
    public R updateInfo(@RequestBody Rider rider) {
        System.out.println(rider);
        riderService.updateById(rider);
        return R.ok();
    }
}
